from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
from . import constants
from utils import tjws
from celery_tasks.email.tasks import send_verify_email
from meiduo.apps.users.models import User
from django.core.mail import send_mail
from django.conf import settings

from utils.jwt_token import generate_jwt_token


class UserCreateSerializer(serializers.Serializer):
    # 定义属性
    id=serializers.IntegerField(read_only=True)
    #输出口令
    token=serializers.CharField(read_only=True)
    username = serializers.CharField(
        min_length=5,
        max_length=20,
        error_messages={
            'min_length': '用户名要求是5-20个字符',
            'max_length': '用户名要求是5-20个字符',
        }
    )
    password = serializers.CharField(
        min_length=8,
        max_length=20,
        error_messages={
            'min_length': '密码要求是8-20个字符',
            'max_length': '密码要求是8-20个字符',
        },
        write_only=True
    )
    password2 = serializers.CharField(
        min_length=8,
        max_length=20,
        error_messages={
            'min_length': '确认密码要求是8-20个字符',
            'max_length': '确认密码要求是8-20个字符',
        },
        #属性只接收客户端的数据，不向客户端响应
        write_only=True
    )
    sms_code = serializers.IntegerField(write_only=True)
    mobile = serializers.CharField()
    allow = serializers.BooleanField(write_only=True)


    # 验证validate_**
    # 验证用户名是否存在
    def validate_username(self, value):
        count = User.objects.filter(username=value).count()
        if count > 0:
            raise serializers.ValidationError('用户名已经存在')
        return value
    def validated_mobile(self,value):
        count = User.objects.filter(mobile = value).count()
        if count >0 :
            raise serializers.ValidationError('手机号码已经存在')
        return value
    def validate_allow(self,value):
        if not value:
            raise serializers.ValidationError("请先阅读并同意协议")
        return value
    def validate(self, attrs):
        password = attrs.get('password')
        password2 = attrs.get('password2')
        if password != password2:
            raise serializers.ValidationError("两个密码不一致")
        sms_code_request = attrs.get('sms_code')
        mobile = attrs.get('mobile')
        redis_cli = get_redis_connection('sms_code')
        sms_code_redis = redis_cli.get('sms_code'+mobile)
        if not sms_code_redis:
            raise serializers.ValidationError("短信验证码已经过期")
        if int(sms_code_redis) != int(sms_code_request):
            raise serializers.ValidationError("短信验证码错误")
        return attrs


    def create(self, validated_data):
        user = User()
        user.username = validated_data.get('username')
        user.mobile = validated_data.get('mobile')
        user.set_password(validated_data.get('password'))
        user.save()
        # 当用户注册成功后，认为登录，则需要进行状态保持===>获取token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        return user
class UserDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'email', 'email_active']

# class EmailSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = User
#         fields = ['email']
#         def update(self,instance,validated_data):
#             email = validated_data.get('email')
#             instance.email=email
#             msg = '<a href="http://www.itcast.cn/subject/pythonzly/index.shtml" target="_blank">点击激活</a>'
#             send_mail('注册s激活', '', settings.EMAIL_FROM, ['baichuangege@163.com'], html_message=msg)
#             return instance
class EmailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['email']

    def update(self, instance, validated_data):
        email = validated_data.get('email')
        instance.email = email
        instance.save()

        # 发送激活邮件
        # send_mail('美多aa商城-邮箱激活','',settings.EMAIL_FROM,[email],html_message='<a>你好</a>')
        # 发邮件耗时，加入celery中
        # url = instance.verify_email_url()
        # send_verify_email.delay(email, url)
        url = instance.verify_email_url()
        send_verify_email.delay(email,url)

        return instance

class EmailVerifySerializer(serializers.Serializer):
    # 接收激活参数
    token = serializers.CharField(max_length=200)

    # 验证激活参数是否有效
    def validate_token(self, value):
        data_dict = tjws.loads(value, constants.VERIFY_EMAIL_EXPIRES)
        if data_dict is None:
            raise serializers.ValidationError('激活链接已经失效')
        # value =
        return data_dict.get('user_id')

    # 激活：修改用户的email_active属性
    def create(self, validated_data):
        user = User.objects.get(pk=validated_data.get('token'))
        user.email_active = True
        user.save()
        return user